import { defineStore} from "pinia";
import{ref,watch} from 'vue';

function initState(){
return{isCollapse:false,

    tags:[{
        path:'/home',
        name:'home',
        label:'首页',
        icon:'home'
    }],
    currentMenu:null,

    menuList:[],
    token:'',
    routerList:[],
}

}
export const useAllDtaStore=defineStore('allData',()=>{
    // ref类似于state属性
    // computed类似于getters属性
    // function类似于actions属性
const state =ref(initState())
watch(state,(newObj)=>{
   if(!newObj.token)return;
    localStorage.setItem('token',newObj.token)
},{deep:true}
)

// 动态路由
function addMenu(router,type){
    if(type==='refresh'){
      if(JSON.parse(localStorage.getItem('store'))){
         state.value=JSON.parse(localStorage.getItem('store'));
         state.value.value.routerList=[]

      } else{
        return
      }
    }
    const menu =state.value.menuList;
    const module =import.meta.glob('../views/**/*.vue')
    const routeArr=[]
    menu.forEach(item=>{
        if(item.children){
            item.children.forEach((val)=>{
                let url=`../views/${item.url}.vue`
                val.component=module[url]
                routeArr.push(...item.children)
            })
        } else{
            let url=`../views/${item.url}.vue`;
            item.component=module[url];
            routeArr.push(item)

        }
    })
//    router.addRoute('main',item)
//     state.value.routerList=[]
//     let routers=router.getRoutes();
//     routers.forEach(item=>{
//         if(item.name=='main'||item.name=='login'){
//          return
//         }else{
//             router.removeRoute(item.name)
//         }
//     })
    routeArr.forEach(item=>{
       state.value.routerList.push(router.addRoute('main',item))
    })
}
    function selectMenu(val){
        if(val.name==='home'){
            state.value.currentMenu=null;
        }else{
              state.value.currentMenu=val;
          let index=  state.value.tags.findIndex(item=>item.name===val.name)
          index===-1?state.value.tags.push(val):"";
        }
    }

    function updateMenu(tag){
        let index=state.value.tags.findIndex(item=>item.name===tag.name)

        state.value.tags.splice(index,1)
    }
    function updateMenuList(menuList){
        state.value.menuList=menuList;

    }
    function clean(){
        state.value.routerList.forEach(item=>{
          console.log(item)
            
        })
        state.value=initState()
        // 删除缓存
        localStorage.removeItem('store')
    }
    
    return{state
        ,selectMenu,
        updateMenu,
        updateMenuList,
        addMenu,
        clean
    }
})